import { SETADDRESS, SETADDRESSID } from '../mutation-type'
import {post} from '@/utils/axios'

// import { getToken } from '@/utils/getToken'

function mutationFunc (context, res) {
  if (res.status >= 0) {
    context.commit('SETADDRESS', res.result)
    /**********************************/
    const arr = res.result.filter(item => {
      return item.isDefault === true
    })
    if (arr.length > 0) {
      context.commit('SETADDRESSID', arr[0].id)
    } else {
      context.commit('SETADDRESSID', '')
    }
  }
}

const module = {
  namespaced: true, // 命名空间
  state: {
    areaLists: [],
    chosenAddressId: '',
    disabledList: []
  },
  actions: {
    getAddressAction (context, payload) {
      post({
        url: '/hybrid/uni/getarea',
        method: 'POST'
      }).then(res => {
        mutationFunc(context, res)
      })
    },
    modifyArea (context, payload) {
      // 修改默认地址
      post({
        url: '/hybrid/uni/modify-area',
        data: { id: payload.id }
      }).then(res => {
        // mutationFunc(context, res)
        context.dispatch('getAddressAction')
      })
    },
    deleteArea (context, payload) {
      post({
        url: '/hybrid/uni/delete-area',
        data: { id: payload }
      }).then(res => {
        // mutationFunc(context, res)
        context.dispatch('getAddressAction')
      })
    },
    deleteSelectArea (context, payload) {
      post({
        url: '/hybrid/uni/delete-select-area',
        data: payload
      }).then(res => {
        // context.dispatch('addressModule/getAddressAction')
        // NOTE: 本模块内不用加名字
        context.dispatch('getAddressAction')
      })
    },
    addArea (context, payload) {
      post({
        url: '/hybrid/uni/add-area',
        data: { content: {  ...payload } }
      }).then(res => {
        // console.log(res)
        context.dispatch('getAddressAction')
      })
    },
    modifyItem (context, payload) {
      // 修改单个地址
      post({
        url: '/hybrid/uni/modify-item',
        data: { ...payload }
      }).then(res => {
        // mutationFunc (context, res)
        context.dispatch('getAddressAction')
      })
    }
  },
  mutations: {
    [SETADDRESS] (state, payload) {
      state.areaLists = payload
    },
    [SETADDRESSID] (state, payload) {
      state.chosenAddressId = payload
    }
  },
  getters: {
    getItemById: (state) => (id) => {
      return state.areaLists.find(todo => todo.id === id)
    }
  }
}

export default module
